import { MpSdk } from "../sdk"
import BundleConnector from "./BundleConnector"
import BundleMessengerFactoryFetcher from "./BundleMessengerFactoryFetcher"
import DynamicLibLoader from "./utils/DynamicLibLoader"
declare global {
  interface Window {
    "sdk-client": any
  }
}

const loaderJS = new DynamicLibLoader()
export default {
  connect: async (connector: BundleConnector, message: BundleMessengerFactoryFetcher) => {
    let sdk: any
    try {
      sdk = await connector.connect()
    } finally {
      connector.cancelConnecting()
    }
    const { scriptUrl, serializedInterface } = sdk
    const factory = message.getFactory(sdk)
    let SdkBuilder: any
    if (!scriptUrl) throw new Error("Unabled to load the sdk")
    try {
      const sdkClient = await loaderJS.load(scriptUrl, "sdk-client")
      if (sdkClient && sdkClient.SdkBuilder && "function" == typeof sdkClient.SdkBuilder) SdkBuilder = sdkClient.SdkBuilder
    } catch (e) {
      throw Error(`Could not load the sdk from ${e}`)
    }
    return new SdkBuilder(factory).build(serializedInterface) as MpSdk
  }
}
